package com.example.yurpceasy.bootstrap;

import com.example.yurpceasy.RpcApplication;
import com.example.yurpceasy.config.RegistryConfig;
import com.example.yurpceasy.config.RpcConfig;
import com.example.yurpceasy.model.ServiceMetaInfo;
import com.example.yurpceasy.model.ServiceRegisterInfo;
import com.example.yurpceasy.register.LocalRegistry;
import com.example.yurpceasy.register.Registry;
import com.example.yurpceasy.register.RegistryFactory;
import com.example.yurpceasy.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * 服务提供者初始化
 */
public class ProviderBootstrap {

    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList){
        // RPC 框架初始化
        RpcApplication.init();
        // 全局配置
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        // 注册服务
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            // 本地注册
            LocalRegistry.register(serviceRegisterInfo.getServiceName(),serviceRegisterInfo.getImplClass());

            // 服务中心注册
            RegistryConfig rcpRegisterConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(rcpRegisterConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceRegisterInfo.getServiceName());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException("服务注册失败");
            }
        }

        // 启动服务器
        VertxTcpServer tcpServer = new VertxTcpServer();
        tcpServer.doStart(rpcConfig.getServerPort());
    }

}
